/*
 * @Author: kincaid
 * @Date: 2021-08-22 21:38:57
 * @LastEditors: kincaid
 * @LastEditTime: 2021-08-24 00:03:33
 * @Description: file content
 */
// pages/repast/repast.js
const app = getApp()
import mqtt from '../../utils/mqtt.js';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
const host = 'wxs://on4ng0.cn1.mqtt.chat/mqtt';
  Page({
  /**
   * 组件的初始数据
   */
  data: {
    peopleList: [6],
    allPrice: 0,
    active: '',
    allFoodNum: 0,
    orderList: [{
      idx: 0,
      imgUrl: '',
      name: '红烧大螃蟹',
      price: 40,
      num: 0
    }],
    foodList: [{
        idx: 0,
        id: 1,
        imgUrl: '',
        sale: 0,
        name: '红烧大螃蟹',
        price: 40,
        num: 0
      },
      {
        idx: 1, 
        id: 2,
        sale: 0,
        imgUrl: '',
        name: '红烧狮子头',
        price: 45,
        num: 0
      }, {
        idx: 2,
        imgUrl: '',
        id: 3,
        sale: 0,
        name: '香辣红烧肉',
        price: 25,
        num: 0
      }, {
        idx: 3,
        id: 4,
        sale: 0,
        imgUrl: '',
        name: '红烧牛肉丝',
        price: 32,
        num: 0
      }
    ],
    noticeOrder:'快点下单吧',
    user:'',
    onlineList:[],
    rankList: [{
      id: 1,
      sale: 10,
      name: '红烧大螃蟹',
    },
    {
      id: 2,
      sale: 0,
      name: '红烧狮子头',
    }, {
      id: 3,
      sale: 0,
      name: '香辣红烧肉',
    }, {
      id: 4,
      sale: 0,
      name: '红烧牛肉丝',
    }
  ],
    //mqtt 所需参数
    client: null,
    //记录重连的次数
    reconnectCounts: 0,
    //MQTT连接的配置
    options: {
      protocolVersion: 4, //MQTT连接协议版本 'test'+new Date().getTime() 
      clientId: 'test'+new Date().getTime()+'@'+'on4ng0',
      clean: false,
      password: 'YWMtEa31WvKOEeuKAoGk5jJh8ajI7Z3Lsk1KtyzEZ3_lc1QQiFTg8o4R65I2hUgU8EeNAwMAAAF7AE6YsgBPGgD4W3LbZaK49g85xoMrFu_2OJLvHARRy4p_REb8Sr7pIw',
      username: 'test',
      reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
      connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
      resubscribe: true //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
    }
  },
  async onLoad(){
    this.setData({
      active: 'tab1',
    })
    //初始化信息保持连接
    //初始化名称
    if(!(wx.getStorageSync('username'))){
      wx.setStorageSync("username",getRandomName())
      wx.showModal({
        content: "您的昵称是"+wx.getStorageSync('username'),
        showCancel: false,
      });
    }
    //获取用户名称
    this.setData({
      user: wx.getStorageSync('username')
    })
    this.onClick_connect()

    //测试云函数
    let that = this
    await this.onGetOpenid()
    console.log(app.globalData.openid)

    wx.cloud.callFunction({
      name: 'updateOrder',
      data: {
        openid: 'oyUbv0JdopprlPBZjJZsGU-LMCJ8',
        list: that.data.rankList
      },
      success: res => {
        console.log('[云函数] [update] order openid: ', res)
        console.log(res)

        
      },
      fail: err => {
        console.error('[云函数] [update] 调用失败', err)

      }
    })
    
  },
  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        console.log(res)
        app.globalData.openid = res.result.openid
        // wx.navigateTo({
        //   url: '../userConsole/userConsole',
        // })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        // wx.navigateTo({
        //   url: '../deployFunctions/deployFunctions',
        // })
      }
    })
  },
  /**
   * 组件的方法列表
   */
  userLogin(){
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        console.log(res)
        app.globalData.openid = res.result.openid
        // wx.navigateTo({
        //   url: '../userConsole/userConsole',
        // })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        // wx.navigateTo({
        //   url: '../deployFunctions/deployFunctions',
        // })
      }
    })
  },
   onClick_connect: function() {
    var that = this;
    //开始连接
    this.data.client = mqtt.connect(host, this.data.options);
    this.data.client.on('connect', function(connack) {
      // wx.showToast({
      //   title: '连接成功'
      // })
      that.onClick_SubOne()
    })


    //服务器下发消息的回调
    that.data.client.on("message", function(topic, payload) {
      console.log(" 收到 topic:" + topic + " , payload :" + payload)
      let msg = JSON.parse(payload)
      if(topic=='user'){
        that.handleUserMqtt(msg)
      }
      if(topic=='order'){
        that.handleOrderMqtt(msg)
      }
      if(topic=='pay'){
        that.handlePayMqtt(msg)
      }
      if(topic=='online'){
        that.handleOnlineMqtt(msg)
      }
      // wx.showModal({
      //   content: " 收到topic:[" + topic + "], payload :[" + payload + "]",
      //   showCancel: false,
      // });
    })


    //服务器连接异常的回调
    that.data.client.on("error", function(error) {
      console.log(" 服务器 error 的回调" + error)

    })

    //服务器重连连接异常的回调
    that.data.client.on("reconnect", function() {
      console.log(" 服务器 reconnect的回调")

    })


    //服务器连接异常的回调
    that.data.client.on("offline", function(errr) {
      console.log(" 服务器offline的回调")

    })


  },
  onClick_SubOne: function() {
    let that = this
    if (this.data.client && this.data.client.connected) {
      //仅订阅单个主题
      this.data.client.subscribe({
        'order': {
          qos: 1
        },
        'user': {
          qos: 1
        },
        'pay':{
          qos: 1
        },
        'online':{
          qos: 1
        }
      }, function(err, granted) {
        if (!err) {
          let obj = {username:wx.getStorageSync('username')}
          that.onClick_PubMsg('user',JSON.stringify(obj))
          // wx.showToast({
          //   title: '连接成功了'
          // })
        } else {
          wx.showToast({
            title: '订阅主题失败',
            icon: 'fail',
            duration: 2000
          })
        }
      })
    } else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  },
  onClick_PubMsg: function(topic,msg) {
    if (this.data.client && this.data.client.connected) {
      this.data.client.publish(topic,msg);

      // wx.showToast({
      //   title: '发布成功'
      // })
    } else {
      wx.showToast({
        title: '请先连接服务器',
        icon: 'none',
        duration: 2000
      })
    }
  },
  tabChange(){
    //获取新的排行榜数据
    
  },
  handleOnlineMqtt(opt){
    if(opt.length>=this.data.onlineList.length){
      this.setData({
        onlineList: opt
      })
    }
  },
  handleUserMqtt(obj){
    let list = this.data.onlineList
    list.push(obj.username)
    //去重
    list = [...new Set(list)]
    this.setData({
      onlineList: list
    })
    //当有新人进来 同步下排行和在线榜数据
    this.onClick_PubMsg('online',JSON.stringify(list))

    let _obj = this.data.rankList
    this.onClick_PubMsg('order',JSON.stringify(_obj))
  },
  handleOrderMqtt(opt){
    //处理订单数据
    let list = this.data.rankList
    opt.forEach((v,i)=>{
      list[i].sale = v.sale
    })
    list.sort(this.compare("sale"))
    this.setData({
      rankList: list
    })

  },
  compare(property){
    return function(obj1,obj2){
      var value1 = obj1[property];
      var value2 = obj2[property];
      return value2 - value1;     // 升序
    }
  },
  handlePayMqtt(opt){
    //接收支付后的通知打家
    opt.list.forEach((v,i)=>{
      setTimeout(()=>{
        Notify(`${opt.name}下单了${v.num}份${v.name}`);
      },4000*i)

    })


  },
  payOrder(){
    //模拟支付成功 重置数据 提交到数据库
    //发通知
    let obj = {
      name: this.data.user,
      list: this.data.orderList
    }
    obj = JSON.stringify(obj)
    this.onClick_PubMsg('pay',obj)
    //请求数据后clear 信息
    wx.showToast({
      title: '支付成功'
    }) 
    this.resetFoodList()
    
    


  },
  resetFoodList(){
    this.orderList = []
    let list = this.data.foodList
    list.forEach(v => {
      v.num = 0
    })
    let obj = this.data.rankList
    this.onClick_PubMsg('order',JSON.stringify(obj))
    
    this.setData({
      foodList: list,
      allPrice: 0,
      allFoodNum: 0
    })
  },
  addNum: function (e) {
    let query = e.currentTarget.dataset['add']
    this.data.foodList[query.idx].num++
    this.data.rankList[query.idx].sale++
    this.data.allPrice = this.data.allPrice + query.price
    this.data.allFoodNum++
    this.data.orderList = this.data.foodList.filter(item => {
      return item.num > 0
    })
    this.setData({
      'foodList': this.data.foodList,
      'allPrice': this.data.allPrice,
      'allFoodNum': this.data.allFoodNum,
      'orderList': this.data.orderList,
    })
   
  },
  subNum: function (e) {
    let query = e.currentTarget.dataset['sub']
    this.data.foodList[query.idx].num--
    this.data.rankList[query.idx].sale--
    this.data.allPrice = this.data.allPrice - query.price
    this.data.allFoodNum--
    this.data.orderList = this.data.foodList.filter(item => {
      return item.num > 0
    })
    this.setData({
      'foodList': this.data.foodList,
      'allPrice': this.data.allPrice,
      'allFoodNum': this.data.allFoodNum,
      'orderList': this.data.orderList,

    })
    this.onClick_PubMsg('order','1232123')

  }
})

function getRandomName(){
  var firstNames = new Array(
  '赵',    '钱',    '孙',    '李',    '周',    '吴',    '郑',    '王',    '冯',    '陈',
  
  '褚',    '卫',    '蒋',    '沈',    '韩',    '杨',    '朱',    '秦',    '尤',    '许',
  '何',    '吕',    '施',    '张',    '孔',    '曹',    '严',    '华',    '金',    '魏',
  
  '陶',    '姜',    '戚',    '谢',    '邹',    '喻',    '柏',    '水',    '窦',    '章',
  '云',    '苏',    '潘',    '葛',    '奚',    '范',    '彭',    '郎',    '鲁',    '韦',
  
  '昌',    '马',    '苗',    '凤',    '花',    '方',    '俞',    '任',    '袁',    '柳',
  '酆',    '鲍',    '史',    '唐',    '费',    '廉',    '岑',    '薛',    '雷',    '贺',
  
  '倪',    '汤',    '滕',    '殷',    '罗',    '毕',    '郝',    '邬',    '安',    '常',
  '乐',    '于',    '时',    '傅',    '皮',    '卞',    '齐',    '康',    '伍',    '余',
  
  '元',    '卜',    '顾',    '孟',    '平',    '黄',    '和',    '穆',    '萧',    '尹',
  '欧阳',  '慕容'
  );
  var secondNames =  new Array(
  '子璇', '淼', '国栋', '夫子', '瑞堂', '甜', '敏', '尚', '国贤', '贺祥', '晨涛',
  '昊轩', '易轩', '益辰', '益帆', '益冉', '瑾春', '瑾昆', '春齐', '杨', '文昊',
  '东东', '雄霖', '浩晨', '熙涵', '溶溶', '冰枫', '欣欣', '宜豪', '欣慧', '建政',
  '美欣', '淑慧', '文轩', '文杰', '欣源', '忠林', '榕润', '欣汝', '慧嘉', '新建',
  '建林', '亦菲', '林', '冰洁', '佳欣', '涵涵', '禹辰', '淳美', '泽惠', '伟洋',
  '涵越', '润丽', '翔', '淑华', '晶莹', '凌晶', '苒溪', '雨涵', '嘉怡', '佳毅',
  '子辰', '佳琪', '紫轩', '瑞辰', '昕蕊', '萌', '明远', '欣宜', '泽远', '欣怡',
  '佳怡', '佳惠', '晨茜', '晨璐', '运昊', '汝鑫', '淑君', '晶滢', '润莎', '榕汕',
  '佳钰', '佳玉', '晓庆', '一鸣', '语晨', '添池', '添昊', '雨泽', '雅晗', '雅涵',
  '清妍', '诗悦', '嘉乐', '晨涵', '天赫', '玥傲', '佳昊', '天昊', '萌萌', '若萌'
  );
  
      var firstLength = firstNames.length;
      var secondLength = secondNames.length;
      
      var i = parseInt(  Math.random() * firstLength );
      var j = parseInt(  Math.random() * secondLength );
      
      var name = firstNames[i]+secondNames[j];
      
      return name;
      
  }//end getRandomName